﻿using Microsoft.Phone.Controls;

namespace MvvmCrystalTool
{
    public class MvvmNavigatablePage : PhoneApplicationPage
    {
        protected INavigationService Navigator { get; set; }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            DoNavigatedTo();

            base.OnNavigatedTo(e);
        }

        private void DoNavigatedTo()
        {
            if (Navigator == null)
                return;

            var viewModel = Navigator.GetDataContext(NavigationContext);

            if (viewModel is INavigatableViewModel)
                (viewModel as INavigatableViewModel).OnNavigatedTo();

            if (viewModel != null)
                DataContext = viewModel;
        }
    }
}
